package xyz.holee.hoimclient

import android.annotation.SuppressLint
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.webkit.JavascriptInterface
import android.webkit.WebView
import android.widget.Toast
import java.text.SimpleDateFormat
import java.util.Date

class MainActivity : AppCompatActivity() {
    @SuppressLint("SetJavaScriptEnabled", "JavascriptInterface")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val webView: WebView = findViewById(R.id.webView)
        WebView.setWebContentsDebuggingEnabled(true)
        webView.settings.javaScriptEnabled = true
        webView.addJavascriptInterface(JSInterface(this), "android")
        webView.loadUrl("file:///android_asset/index.html")
    }
}

class MyDatabaseHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
    companion object {
        private const val DATABASE_NAME = "db.db"
        private const val DATABASE_VERSION = 1
    }

    override fun onCreate(db: SQLiteDatabase) {
        val tableExistsQuery = "SELECT `name` FROM `sqlite_master` " +
                "WHERE `type` = 'table' AND `name` = 'chat_history'"
        val cursor = db.rawQuery(tableExistsQuery, null)
        val tableExists = cursor.count > 0
        cursor.close()

        if (!tableExists) {
            // 数据表不存在，执行创建表的操作
            val createTableQuery = "CREATE TABLE `chat_history`(" +
                    "`id` INTEGER PRIMARY KEY AUTOINCREMENT," +
                    "`friend_name` TEXT," +
                    "`to_or_from` INT(2)," +
                    "`send_datetime` INTEGER," +
                    "`message` TEXT)"
            db.execSQL(createTableQuery)
        }
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
    }
}

class JSInterface(private val activity: MainActivity) {
    @JavascriptInterface
    fun show_toast_long(message: String) {
        Toast.makeText(this.activity, message, Toast.LENGTH_LONG).show()
    }
    @JavascriptInterface
    fun show_toast_short(message: String) {
        Toast.makeText(this.activity, message, Toast.LENGTH_SHORT).show()
    }
    @SuppressLint("Range")
    @JavascriptInterface
    fun get_chat_list(): String {
        val dbHelper = MyDatabaseHelper(this.activity)
        val db = dbHelper.writableDatabase
        val cursor = db.rawQuery(
            "SELECT `friend_name` " +
                    "FROM `chat_history` " +
                    "GROUP BY `friend_name`", null)
        val data: ArrayList<String> = ArrayList()
        if (cursor.moveToLast()) {
            do {
                val friend_name: String = cursor.getString(cursor.getColumnIndex("friend_name"))
                data.add(friend_name)
            } while (cursor.moveToPrevious())
        }
        cursor.close()
        db.close()
        return data.joinToString(",")
    }
    @JavascriptInterface
    fun get_pref(key: String): String {
        val pref = this.activity.getPreferences(Context.MODE_PRIVATE)
        val value = pref.getString(key, "")
        if (value.isNullOrEmpty()) {
            return ""
        }
        return value
    }
    @JavascriptInterface
    fun get_current_username(): String {
        val pref = this.activity.getPreferences(Context.MODE_PRIVATE)
        val chat_list = pref.getString("username", "")
        if (chat_list.isNullOrEmpty()) {
            return ""
        }
        return chat_list
    }
    @JavascriptInterface
    fun save_config(wsUrl: String, port: String, username: String) {
        val pref = this.activity.getPreferences(Context.MODE_PRIVATE)
        val edit = pref.edit()
        edit.putString("server_ip", wsUrl)
        edit.putString("port", port)
        edit.putString("username", username)
        edit.apply()
    }
    @SuppressLint("Range", "SimpleDateFormat")
    @JavascriptInterface
    fun get_chat_history(target: String, count: Int): String {
        val dbHelper = MyDatabaseHelper(this.activity)
        val db = dbHelper.writableDatabase
        val cursor = db.rawQuery(
            "SELECT `friend_name`, " +
                    "`to_or_from`, " +
                    "`send_datetime`, " +
                    "`message` " +
                    "FROM `chat_history` " +
                    "WHERE `friend_name` = '${target}' " +
                    "ORDER BY `send_datetime` DESC " +
                    "LIMIT $count", null)
        val data: ArrayList<String> = ArrayList()
        if (cursor.moveToLast()) {
            do {
                var friend_name: String = cursor.getString(cursor.getColumnIndex("friend_name"))
                val to_or_from: Int = cursor.getInt(cursor.getColumnIndex("to_or_from"))
                val send_datetime: Long = cursor.getLong(cursor.getColumnIndex("send_datetime"))
                val message: String = cursor.getString(cursor.getColumnIndex("message"))
                val date = Date(send_datetime)
                val datetime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date)
                if (to_or_from == 0) {
                    friend_name = "我"
                }
                data.add("${friend_name}{{||}}${datetime}{{||}}${message}")
            } while (cursor.moveToPrevious())
        }
        cursor.close()
        db.close()
        return data.joinToString("{{|}}")
    }
    @JavascriptInterface
    fun save_history(to_or_from: Int, target_username: String, message: String) {
        val dbHelper = MyDatabaseHelper(this.activity)
        val db = dbHelper.writableDatabase
        val timestamp = System.currentTimeMillis()
        db.execSQL("INSERT INTO `chat_history`(" +
                "`to_or_from`, " +
                "`friend_name`, " +
                "`send_datetime`, " +
                "`message`) VALUES (" +
                "'${to_or_from}', " +
                "'${target_username}', " +
                "'${timestamp}', " +
                "'${message}')")
        db.close()
    }
}
